/**
Current location JavaScript object
 */
function CurrentLocation()
{
    this.lat = null;
    this.lng = null;
    this.alt = null;
    this.speed = null;
    this.tableId = null;
}

/**
  What to do when we can't get user's location
 */
function handleGeoLocationError(error)
{
    switch (error.code)
    {
    case error.PERMISSION_DENIED:
        alert("User did not share geoLocation data");
        break;

    case error.POSITION_UNAVAILABLE:
        alert("could not detect current position");
        break;

    case
        error.TIMEOUT:
        alert("retrieving position timed out");
        break;

    default:
        alert("unknown error");
        break;
    }
}

/**
  Storesuser's current location in hidden form fields.
  TODO Make use of sessionStorage here
 */
function setLatLngFields(p)
{
    $("#latitude")
        .val(p.lat);
    $("#longitude")
        .val(p.lng);
}

/**
  Load States select box
 */
function loadStatesSelect()
{
    $.ajax({
	url : 'http://eratos-ecelis.dotcloud.com/v1/cities?callback=?',
        dataType : 'jsonp',
	data: 'data'
    });
    /*
    var options = '';
    for (var i = 0; i < places.states.length; i++)
    {
        options = '<option ' + 'value="' + places.states[i].id + '">' + places.states[i].name + '</option>';
        $(options)
            .appendTo("select#select-state");
    }
    */
}


/**
  Load Cities select box
 */
function loadCitiesSelect(cities)
{
    var options = '';
    options = '<option>-- SELECT CITY --</option>';
    $(options)
        .appendTo("select#select-municipality");
    for (var i = 0; i < cities[0].municipalities.length; i++)
    {
        options = '<option ' + 'value="' + cities[0].municipalities[i].id + '">' + cities[0].municipalities[i].name + '</option>';
        $(options)
            .appendTo("select#select-municipality");
    }
}

/**
  Center map to a selected city
  @param city, is a JavaScript object holding geo data
 */
function getSelectedCity(p)
{
    var p = new CurrentLocation();
    $("#latitude")
        .val(city.lat);
    $("#longitude")
        .val(city.lng);
    $("#tableId")
        .val(city.tableId);
    p = city;
    initializeMap(p);
}

function getObjects(obj, key, val)
{
    var objects = [];
    for (var i in obj)
    {
        if (!obj.hasOwnProperty(i))
        {
            continue;
        }
        if (typeof obj[i] == 'object')
        {
            objects = objects.concat(getObjects(obj[i],
            key,
            val));
        }
        else if (i == key && obj[key] == val)
        {
            objects.push(obj);
        }
    }
    return objects;
}

/**
  Initialize the App
  @param p, is a JavaScript object holding geo data.
 */
function initialize(p)
{

    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(function (position)
        {
            p.lat = position.coords.latitude;
            p.lng = position.coords.longitude;
            initializeMap(p);
            setLatLngFields(p);
        });
    }
    loadStatesSelect();
    $("#select-state")
        .change(function (p)
    {
        var cities = getObjects(places, 'id', $(this)
            .val());
        $("#select-municipality option")
            .remove();
        loadCitiesSelect(cities);
    });
    $("#select-municipality")
        .change(function (p)
    {
        var city = getObjects(places, 'id', $(this)
            .val());
        getSelectedCity(city[0]);
    });
}

/**
  Initialize the map DIV
  @param p, JavaScript object holing geo data
 */
function initializeMap(p)
{
    var tableId = $("#tableId")
        .val();
    var mapOptions = {
        center: new google.maps.LatLng(p.lat, p.lng),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    var tableLayer = new google.maps.FusionTablesLayer(
    {
        query: {
            select: 'ROWID,description,name,color,votes,geometry',
            from: tableId
        }
    });

    tableLayer.setMap(map);
}
